#ifndef OSGWIDGET_H
#define OSGWIDGET_H

#include "common.h"

class osgWidget : public QWidget, public osgViewer::CompositeViewer
{
public:
    osgWidget(): QWidget()
    {
        initViewerCamera();
        setViewerData();
        setViewerLayout();
        setTimer();
    }
    virtual void paintEvent( QPaintEvent* event )
    { frame(); }
protected:
    void initViewerCamera()
    {
        setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
        // disable the default setting of viewer.done() by pressing Escape.
        setKeyEventSetsDone(0);

        osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->windowName = "";
        traits->windowDecoration = false;
        traits->x = 0;
        traits->y = 0;
        traits->width = 800;
        traits->height = 600;
        traits->doubleBuffer = true;
        traits->alpha = ds->getMinimumNumAlphaBits();
        traits->stencil = ds->getMinimumNumStencilBits();
        traits->sampleBuffers = ds->getMultiSamples();
        traits->samples = ds->getNumMultiSamples();
        gw = new osgQt::GraphicsWindowQt(traits.get());

        view = new osgViewer::View;
        addView( view );

        osg::Camera* camera = view->getCamera();
        camera->setGraphicsContext(gw);

        camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) );
        camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
        camera->setProjectionMatrixAsPerspective(
            30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );

    }
    void setViewerLayout()
    {
        QGridLayout* grid = new QGridLayout;
        grid->addWidget( gw->getGLWidget(), 0, 0 );
        setLayout( grid );
    }
    void setTimer()
    {
        connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
        _timer.start( 10 );
    }
    void setViewerData()
    {

        view->setSceneData(osgDB::readNodeFile("D:/OpenSceneGraph-Data/cow.osgt") );
        view->addEventHandler( new osgViewer::StatsHandler );
        view->setCameraManipulator( new osgGA::TrackballManipulator );
    }

private:
    QTimer _timer;
    osgQt::GraphicsWindowQt* gw;
    osgViewer::View* view;
};

#endif // OSGWIDGET_H
